package com.jvtd.baseProject.base;


import com.jvtd.baseProject.bean.db.User;
import com.jvtd.baseProject.data.DbManager;
import com.jvtd.baseProject.constants.App;

import org.litepal.crud.DataSupport;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by Administrator on 2017/10/16.
 * Presenter 基类
 */

public class BasePresenter<V extends MvpView> implements MvpPresenter<V>
{
  /**
   * 获取的页数 default 1
   */
  protected int mPageIndex = 1;
  protected int mPageSize = App.LOAD_NUM;
  protected boolean isLoading = false;// 是否显示LoadingDialog

  private final DbManager mDbManager;
  private final CompositeDisposable mDisposable;
  private V mMvpView;

  @Inject
  public BasePresenter(DbManager dbManager, CompositeDisposable disposable)
  {
    mDbManager = dbManager;
    mDisposable = disposable;
  }

  /**
   * 注册界面方法
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  @Override
  public void onAttach(V mvpView)
  {
    mMvpView = mvpView;
  }

  /**
   * 注销界面方法
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  @Override
  public void onDetach()
  {
    mDisposable.clear();
    mMvpView = null;
  }

  /**
   * 是否已注册界面方法
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  public boolean isAttachView()
  {
    return mMvpView != null;
  }

  /**
   * 获取当前注册界面方法
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  public V getMvpView()
  {
    return mMvpView;
  }

  /**
   * 数据库及网络接口管理
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  public DbManager getDbManager()
  {
    return mDbManager;
  }

  public CompositeDisposable getCompositeDisposable()
  {
    return mDisposable;
  }

  /**
   * 设置用户状态为退出
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  @Override
  public void setUserAsLoggedOut()
  {
    getDbManager().setLoginOut();
  }

  /**
   * 获取当前用户
   *
   * @author Chenlei
   * created at 2018/9/25
   **/
  @Override
  public User getCurrentUser()
  {
    return DataSupport.findFirst(User.class, true);
  }

  /**
   * 判断登录状态
   */
  @Override
  public void checkLoginStatus()
  {
    if (isAttachView()) getMvpView().isLogin(getDbManager().isLogin());
  }

  /**
   * 登出
   */
  @Override
  public void logout(boolean needFinish)
  {
    setUserAsLoggedOut();
    // TODO: 2018/9/25 退出登录 信息的删除及第三方SDK相关操作 
    // 清空部分数据库
    deleteDb();

    if (isAttachView() && needFinish) getMvpView().logoutSuccess();
  }

  private void deleteDb()
  {
    DataSupport.deleteAll(User.class);
  }
}
